﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Movizard.Model
{
    public class MovieCollection : List<MovieCollectionItem>
    {
        private List<MovieCollectionItem> items = new List<MovieCollectionItem>();
        
        public event EventHandler CollectionChanged;

        public void AddFolder(string path)
        {
            string[] dirs = Directory.GetDirectories(path);
            foreach (string dir in dirs)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(dir);
                MovieCollectionItem item = new MovieCollectionItem(dirInfo);
                this.Add(item);
            }
        }

        public void QueryMovies()
        {
            if (items.Count < Properties.Settings.Default.MaxSimultaneousQueries)
                items.AddRange(this.Where(u => u.Status == QueryStatus.Wait).Take(Properties.Settings.Default.MaxSimultaneousQueries - items.Count).ToList());
            foreach (MovieCollectionItem item in items)
            {
                if (item != null)
                {
                    if (item.Status == QueryStatus.Wait)
                    {
                        item.QueryFinished += item_QueryFinished;
                        item.RunQuery();
                    }
                }
            }
        }

        void item_QueryFinished(object sender, EventArgs e)
        {
            items.Remove(sender as MovieCollectionItem);
            QueryMovies();
            if (CollectionChanged != null)
                CollectionChanged(this, EventArgs.Empty);
        }
    }
}
